<template>
  <div class="repair-list-container">
    <div class="app-container">
      <el-card class="box-card">
        <!-- 页头 -->
        <div
          slot="header"
          class="clearfix"
        >
          <span>{{state === 1 ? '待处理报修单' : state === 2 ? '进行中报修单' : '所有报修单'}}</span>
          <div class="form">
            <el-form
              :inline="true"
              :model="queryForm"
              ref="queryForm"
              :rules="queryRules"
              class="demo-form-inline"
            >
              <el-form-item prop='id'>
                <el-input
                  v-model.trim="queryForm.id"
                  placeholder="请输入报修单id"
                  @keyup.enter.native="getQueryFn()"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  @click="getQueryFn()"
                >查询</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>

        <!-- 筛选 -->
        <div class="screen">
          <el-form
            :rules="screenRules"
            inline
            :model="query"
            ref="screenForm"
          >
            <el-form-item
              label="报修类型"
              prop="type_id"
            >
              <el-cascader
                placeholder="请选择报修类型"
                v-model="query.type_id"
                :options="repairTypeList"
                filterable
                clearable
                style="width: 180px"
                :props="{ label: 'name', value: 'id', emitPath: false }"
              ></el-cascader>
            </el-form-item>
            <el-form-item
              label="报修单状态"
              prop="state"
            >
              <el-select
                clearable
                v-model="query.state"
                placeholder="请选择报修单状态"
                style="width: 180px"
              >
                <template v-for="(item, index) in repairState">
                  <el-option
                    :key="index"
                    :label="item"
                    :value="index"
                    v-if="(state===1 && (index==='1'||index==='2')) || (state===2 && (index==='4'||index==='5')) || state===3"
                  >
                  </el-option>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item
              label="报修区域"
              prop="a_id"
            >
              <el-select
                filterable
                clearable
                v-model="query.a_id"
                placeholder="请选择报修区域"
                style="width: 150px"
              >
                <el-option
                  v-for="item in areaOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="维修人员"
              prop="r_number"
            >
              <el-select
                v-model="query.r_number"
                placeholder="请选择维修人员"
                style="width: 150px"
                clearable
              >
                <el-option-group
                  v-for="item in repairerObj"
                  :key="item.type_id"
                  :label="repairerTypeObj[item.type_id]"
                >
                  <el-option
                    v-for="i in item"
                    :key="i.job_number"
                    :label="`${i.job_number}  ${i.name}`"
                    :value="i.job_number"
                  >
                  </el-option>
                </el-option-group>
              </el-select>
            </el-form-item>
            <el-form-item
              label="受理人"
              prop="a_number"
            >
              <el-select
                v-model="query.a_number"
                filterable
                placeholder="请选择受理人"
                style="width: 150px"
                clearable
              >
                <el-option
                  v-for="item in adminList"
                  :key="item.job_number"
                  :label="item.name"
                  :value="item.job_number"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="screenSubmitFn()"
              >提交</el-button>
              <el-button @click="screenResetFn()">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 表格组件 -->
        <div
          class="table"
          style="height: 80%"
          v-if='repairList[0]'
        >
          <el-table
            :data="repairList"
            style="width: 100%"
          >
            <el-table-column
              type="index"
              label="序号"
              min-width="30px"
            >
            </el-table-column>
            <el-table-column
              prop="s_name"
              label="申请人姓名"
              min-width="90px"
            >
            </el-table-column>
            <el-table-column
              prop="type_name"
              label="报修类型"
              min-width="80px"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              prop="place"
              label="报修地点"
              min-width="130px"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              prop="a_id"
              label="报修区域"
              min-width='80px'
            >
              <template v-slot="{row}">
                {{areaOptions[row.a_id]?.label}}
              </template>
            </el-table-column>
            <el-table-column
              prop="phone"
              label="联系电话"
              min-width="110px"
            >
            </el-table-column>
            <el-table-column
              prop="state"
              label="报修状态"
              min-width="80px"
            >
              <template v-slot="{ row }">
                {{ repairState[row.state] }}
              </template>
            </el-table-column>
            <el-table-column
              prop="ctime"
              label="提交时间"
              min-width="145px"
            >
              <template v-slot="{ row }">
                {{ new Date(row.ctime).toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              min-width="125px"
              fixed='right'
            >
              <template v-slot="{ row }">
                <el-button
                  circle
                  size="mini"
                  icon="el-icon-search"
                  @click="
                    $router.push({
                      path: `/repair/info/${row.id}`,
                    })
                  "
                ></el-button>
                <el-button
                  type="primary"
                  circle
                  icon="el-icon-edit"
                  size="mini"
                  @click="updateStateFn(row)"
                ></el-button>
                <el-button
                  v-if="row.state < 3"
                  type="warning"
                  circle
                  icon="el-icon-s-check"
                  size="mini"
                  @click="passBtnFn(row)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-empty
          v-else
          :image-size="200"
        ></el-empty>

        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px; margin-top: 40px"
          v-if="total > query.pagesize"
        >
          <!-- 分页区域 -->
          <el-pagination
            :current-page="query.page"
            :page-sizes="[10, 15, 20, 25]"
            :page-size="query.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            hide-on-single-page
          />
        </el-row>

        <el-dialog
          title="报修单信息"
          :visible.sync="dialogPassValid"
          @close="dialogCloseFn()"
          :show-close='false'
          custom-class='dialog-pass'
        >
          <span slot="footer">
            <el-form
              :model="repairInfo"
              status-icon
              :rules="repairInfoRules"
              ref="repairInfo"
              label-width="100px"
              inline
            >
              <el-form-item
                label="退回原因"
                prop='cause'
              >
                <el-input
                  v-model.trim="repairInfo.cause"
                  show-word-limit
                  maxlength='200'
                  minlength='1'
                  clearable
                  style="width: 350px"
                  @keyup.enter.native="passFn(false)"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  @click="passFn(false)"
                >退回学生处</el-button>
                <el-button @click="passFn(true)">通过</el-button>
              </el-form-item>
            </el-form>
          </span>
          <el-descriptions
            border
            :column='2'
            labelClassName="width-100"
          >
            <el-descriptions-item
              label="报修单号"
              span="2"
            >{{repairInfo.id}}</el-descriptions-item>
            <el-descriptions-item label="申请人学号">{{repairInfo.s_number}}</el-descriptions-item>
            <el-descriptions-item label="申请人姓名">{{repairInfo.s_name}}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{repairInfo.phone}}</el-descriptions-item>
            <el-descriptions-item label="提交时间">{{new Date(repairInfo.ctime).toLocaleString()}}</el-descriptions-item>
            <el-descriptions-item label="报修类型">{{repairInfo.type_name}}</el-descriptions-item>
            <el-descriptions-item label="报修区域">{{areaOptions[repairInfo.a_id]?.label}}</el-descriptions-item>
            <el-descriptions-item
              label="报修地点"
              :span='2'
            >{{repairInfo.place}}</el-descriptions-item>
            <el-descriptions-item
              label="问题描述"
              :span='2'
            >{{repairInfo.problem}}</el-descriptions-item>
            <el-descriptions-item
              label="故障照片"
              :span='2'
            >
              <span
                v-for="(item, index) in repairInfo.p_name"
                :key="index"
              >
                <el-image
                  v-if="item"
                  :src="imgUrl + item"
                  fit='scale-down'
                  style="width: 100px; height: 100px"
                  @click="bigImg = imgUrl + item"
                >
                </el-image>
                <span v-else-if="index === 0">无</span>
              </span>
            </el-descriptions-item>
          </el-descriptions>
        </el-dialog>

        <el-dialog
          :title="'修改报修单状态'"
          :visible.sync="dialogUpdateValid"
          @close="dialogCloseFn()"
          :close-on-click-modal='false'
          :show-close='false'
          custom-class='dialog-update'
        >
          <el-form
            :model="repairStateForm"
            status-icon
            :rules="repairStateRules"
            ref="repairStateForm"
          >
            <el-form-item prop="state">
              <el-radio-group v-model="repairStateForm.newState">
                <template v-for="(item, index) in repairState">
                  <el-radio
                    v-if="index<2 || index>3"
                    :label="index"
                    :key="index"
                  >{{item}}</el-radio>
                </template>

              </el-radio-group>
            </el-form-item>
            <el-form-item class="center">
              <el-button @click="dialogUpdateValid = false">取消</el-button>
              <el-button
                type="primary"
                @click="updateSubmitFn()"
              >{{'修改'}}</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { transTree, repairState, urlArr, imgUrl } from '@/utils'
import {
  examineRepairAPI,
  getRepairListAPI,
  getRepairTypeListAPI,
  queryRepairMAPI,
  screenAdminListAPI,
  screenAreaListAPI,
  screenRepairerListAPI,
  screenRepairerTypeListAPI,
  updateRepairAPI
} from '@/api'
export default {
  name: 'repairList',
  data () {
    const validCause = (rule, value, callback) => {
      if (this.repairInfo.validCause) {
        value ? callback() : callback(new Error('退回原因不能为空！'))
      }
      callback()
    }
    return {
      isAll: true,
      query: {
        page: 1, // 页码
        pagesize: 10, // 每页条数
        r_number: '',
        a_number: '',
        state: ''
      },
      repairTypeList: [], // 报修类型列表
      repairInfo: {
        validCause: false
      }, // 当前审核的报修单信息
      repairInfoRules: {
        id: [
          { required: true, message: 'id不能为空', trigger: 'blur' },
          {
            length: '32',
            type: 'string',
            message: 'id格式有误',
            trigger: 'blur'
          }
        ],
        cause: [
          {
            type: 'string',
            min: 1,
            max: 200,
            message: '退回原因要求1-200字符',
            trigger: 'blur'
          },
          { validator: validCause, trigger: 'blur' }
        ]
      }, // 审核报修单数据验证
      repairList: [], // 报修请求列表
      total: 0, // 数据总数
      queryForm: {
        id: ''
      }, // 查询数据
      queryRules: {
        id: [
          { required: true, message: '报修单id不能为空', trigger: 'blur' },
          {
            min: 32,
            max: 32,
            type: 'string',
            message: 'id要求32个字符',
            trigger: 'change'
          }
        ]
      }, // 查询数据验证
      dialogVisible: false, // dialog 控制
      repairStateForm: {
        id: '',
        state: ''
      }, // 报修单状态信息
      repairStateRules: {
        id: [
          { required: true, message: 'id不能为空', trigger: 'blur' },
          {
            length: '32',
            type: 'string',
            message: 'id格式有误',
            trigger: 'blur'
          }
        ],
        state: [
          { required: true, message: '状态不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 1,
            type: 'string',
            message: '状态要求为1-5',
            trigger: 'blur'
          }
        ]
      }, // 报修单状态验证
      screenRules: {}, // 筛选数据验证
      repairState, // 报修单状态
      repairerObj: [], // 维修人员数据
      adminList: [], // 管理员列表
      repairerTypeObj: {}, // 维修人员类型数据
      dialogPassValid: false, // 审核dialog控制
      dialogUpdateValid: false, // 修改状态dialog控制
      imgUrl,
      timer: null,
      areaOptions: {},
      state: ''
    }
  },
  async created () {
    this.initFn()
    this.getRepairListFn()
    this.getRepairTypeListFn()
    this.getRepairerListFn()
    this.getAdminListFn()
    this.getAreaFn()
  },
  methods: {
    // 每页显示的条数发生改变时触发
    handleSizeChange (newSize) {
      this.query.size = newSize
      this.getRepairListFn() // 获取通知公告列表
    },
    // 当前页面发生改变时触发
    handleCurrentChange (newPage) {
      this.query.page = newPage
      this.getRepairListFn() // 获取通知公告列表
    },
    // 获取报修请求列表
    async getRepairListFn () {
      clearTimeout(this.timer)
      this.timer = setInterval(this.getRepairListFn, 1000 * 60)
      try {
        const { success, code, data } = await getRepairListAPI({
          ...this.query,
          state: this.query.state
            ? parseInt(this.query.state)
            : this.state === 1
              ? -2
              : this.state === 2 ? -3 : ''
        })
        if (success && code === 10000) {
          this.repairList = data.row
          this.total = data.total
          if (this.query.state < 0) this.query.state = ''
        }
      } catch (err) {
        return console.dir(err)
      }
    },
    // 获取维修区域 -> 发送请求
    async getAreaFn () {
      try {
        const { success, code, data } = await screenAreaListAPI({
          page: 1
        })
        if (success && code === 10000) {
          data.forEach((item) => {
            this.$set(this.areaOptions, item.id, {
              value: item.id,
              label: item.name
            })
          })
        }
      } catch (err) {
        return console.dir(err)
      }
    },
    // 获取报修类型列表
    async getRepairTypeListFn () {
      try {
        const { success, code, data } = await getRepairTypeListAPI()
        if (success && code === 10000) {
          this.repairTypeList = transTree(data, '')
        }
      } catch (err) {
        return console.dir(err)
      }
    },
    // 查询报修单
    getQueryFn () {
      try {
        this.$refs.queryForm.validate(async (valid) => {
          if (valid) {
            const { success, code, data } = await queryRepairMAPI(
              {
                ...this.queryForm,
                state: this.query.state
                  ? parseInt(this.query.state)
                  : this.state === 1
                    ? -2
                    : this.state === 2 ? -3 : ''
              }
            )
            if (success && code === 10000) {
              this.repairList = [data]
            }
          }
        })
      } catch (err) {
        return console.dir(err)
      }
    },
    // dialog 关闭
    dialogCloseFn () {
      this.repairInfo = this.$options.data().repairInfo
      this.$refs.repairInfo?.resetFields()

      this.repairStateForm = this.$options.data().repairStateForm
      this.$refs.repairStateForm?.resetFields()
    },
    // 点击筛选按钮 -> 重新获取列表
    screenSubmitFn () {
      this.$refs.screenForm.validate(async (valid) => {
        valid && this.getRepairListFn()
      })
    },
    // 清空筛选数据 -> 重新获取列表
    screenResetFn () {
      this.query = this.$options.data().query
      this.$refs.screenForm?.resetFields()
      this.getRepairListFn()
    },
    // 点击审核  -> 发送请求
    async passFn (isAdopt) {
      this.repairInfo.validCause = !isAdopt
      if (
        !isAdopt &&
        !this.$refs.repairInfo.validate((valid) => valid) &&
        !this.repairInfo.cause
      ) {
        return
      }
      try {
        const { success, code } = await examineRepairAPI({
          id: this.repairInfo.id,
          is_adopt: isAdopt,
          cause: this.repairInfo.cause
        })
        if (success && code === 10000) {
          this.dialogPassValid = false
          this.getRepairListFn()
        }
      } catch (err) {
        return console.dir(err)
      }
    },
    // 点击修改 -> 发送请求
    updateSubmitFn () {
      this.$refs.repairStateForm.validate(async (valid) => {
        if (valid) {
          try {
            const { success, code } = await updateRepairAPI({
              id: this.repairStateForm.id,
              state: this.repairStateForm.state - 0,
              r_number: this.repairStateForm.r_number,
              newState: this.repairStateForm.newState - 0
            })
            if (success && code === 10000) {
              this.getRepairListFn()
              this.dialogUpdateValid = false
            }
          } catch (err) {
            return console.dir(err)
          }
        }
      })
    },
    // 获取维修人员列表
    async getRepairerListFn () {
      try {
        const { success, code, data } = await screenRepairerListAPI()
        if (success && code === 10000) {
          this.repairerObj = data.reduce((obj, item) => {
            obj[item.type_id] = obj[item.type_id] || []
            obj[item.type_id].push(item)
            return obj
          }, {})
        }
      } catch (err) {
        return console.dir(err)
      }
    },
    // 获取管理员列表
    async getAdminListFn () {
      try {
        const { success, code, data } = await screenAdminListAPI()
        if (success && code === 10000) {
          this.adminList = data
        }
      } catch (err) {
        return console.dir(err)
      }
    },
    // 获取维修人员类型列表
    async getRepairerTypeListFn () {
      try {
        const { success, code, data } = await screenRepairerTypeListAPI()
        if (success && code === 10000) {
          data.forEach((item) => {
            this.$set(this.repairerTypeObj, item.id, item.name)
          })
        }
      } catch (err) {
        return console.dir(err)
      }
    },
    // 点击审核按钮
    passBtnFn (data) {
      this.repairInfo = urlArr({ ...data })
      this.dialogPassValid = true
    },
    // 点击修改状态按钮
    updateStateFn (data) {
      this.repairStateForm.state = data.state + ''
      this.repairStateForm.id = data.id
      this.dialogUpdateValid = true
    }, // init
    async initFn () {
      const path = this.$route.path
      switch (path) {
        case '/repair/wait':
          this.state = 1
          break
        case '/repair/underway':
          this.state = 2
          break
        case '/repair/all':
          this.state = 3
          break
      }
    }
  },
  // 销毁实例
  beforeDestroy () {
    clearTimeout(this.timer)
    this.timer = null
  }
}
</script>

<style lang="less" scoped></style>
